<?php
/** @noinspection PhpUnusedParameterInspection */
/** @noinspection PhpUnused */
declare(strict_types=1);

namespace app\shop\model\user;

use app\shop\enums\coupon\CouponStatus;
use app\shop\model\BaseModel;
use app\shop\model\coupon\CouponModel;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;

class UserCouponModel extends BaseModel
{
    use SoftDelete;

    protected $name = 'shop_user_coupon';

    /**
     * 关联优惠券
     * @return BelongsTo
     */
    public function coupon(): BelongsTo
    {
        return $this->belongsTo(CouponModel::class, 'coupon_id', 'id')
            ->bind([
                'name', 'discount_type', 'discount_amount', 'discount_ratio', 'min_price', 'range_type', 'range_goods_ids', 'desc',
                'expiry_type', 'expiry_days'
            ]);
    }

    /**
     * 查询范围：优惠券有效期
     * @param $query
     * @return mixed
     * @noinspection PhpUnused
     */
    public function scopeEffectiveTime($query): mixed
    {
        return $query->whereBetweenTimeField('start_time', 'end_time');
    }

    /**
     * 获取器：优惠券禁用状态
     * @param $value
     * @param $data
     * @return bool
     */
    public function getDisabledAttr($value, $data): bool
    {
        return !($data['status'] === CouponStatus::TO_USE);
    }

    /**
     * 获取器：是否已使用
     * @param $value
     * @param $data
     * @return bool
     */
    public function getUsedAttr($value, $data): bool
    {
        return $data['status'] === CouponStatus::USED;
    }

    /**
     * 获取器：是否已过期
     * @param $value
     * @param $data
     * @return bool
     */
    public function getExpiredAttr($value, $data): bool
    {
        return $data['status'] === CouponStatus::EXPIRED;
    }

    /**
     * 获取器：优惠券是否不可用
     * @param $value
     * @param $data
     * @return bool
     */
    public function getInvalidAttr($value, $data): bool
    {
        return $data['status'] === CouponStatus::INVALID;
    }

    /**
     * 获取器：优惠券可用商品范围
     * @param $value
     * @return array|bool
     */
    public function getRangeGoodsIdsAttr($value): array|bool
    {
        if (empty($value)) {
            return [];
        }

        return explode(',', $value);
    }
}